//
//  ListenPortPacketCenter.m
//  HiQServer
//
//  Created by shoguncao on 12-8-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ListenPortPacketCenter.h"
#import "MacroComd.h"
#import "MiniSocket.h"
#import "MainSocketDelegate.h"
#import "MysqlDB.h"

@implementation ListenPortPacketCenter

- (void)MessageDispatch: (SockPacket *)packet
{
    // 收到用户发包，确认用户自己的 listen 端口
    LISTENPORTHRD *hrd = (LISTENPORTHRD *)[packet.packetContent bytes];
    
    MiniSocket *_sock = [self isBuddyOnline:hrd->userId];
    if (_sock != nil)
    {
        _sock.listenPort = hrd->listenPort;
    }
    else 
    {
        return;
    }
    
    // 查找用户的所有好友
    NSString *userIdStr = [self convertQQNumToString:hrd->userId];
    
    MysqlDB *serverConnect = [[MysqlDB alloc] init];
    [serverConnect connectHost:hostIp connectUser:userName connectPassword:password connectName:dbName];
    
    NSMutableString *sqlQuery = [[NSMutableString alloc] initWithString:@"SELECT * FROM tbFriends WHERE UserId = '"];
    [sqlQuery appendString:userIdStr];
    [sqlQuery appendString:@"'"];
    NSMutableArray *buddyListArray = [serverConnect doDataQuery:sqlQuery];
    
    // 向所有在线好友发送 listen 端口信息
    NSString *ipStr = [_sock.miniAsynSocket connectedHost];
    NSData *ipData = [NSKeyedArchiver archivedDataWithRootObject:ipStr];
    
    NSData *sendPacket = [self createListPortPacket:hrd->userId listenPort:hrd->listenPort ip:ipData];
    NSInteger sendPacketLen = [sendPacket length];
    NSMutableData *sendData = [[NSMutableData alloc] initWithBytes:&sendPacketLen length:sizeof(sendPacketLen)];
    [sendData appendData:sendPacket];
    for (NSInteger i=0; i<[buddyListArray count]; ++i)
    {
        NSMutableArray *buddy = [buddyListArray objectAtIndex:i];
        if ([buddy count] < COLUM_OF_FRIENDID_IN_TBFRIENDS)
            continue;
        NSString *friendIdStr = [buddy objectAtIndex:COLUM_OF_FRIENDID_IN_TBFRIENDS];
        NSInteger friendId = [friendIdStr intValue];
        MiniSocket *sock = [self isBuddyOnline:friendId];
        if (sock != nil)
        {
            [sock.miniAsynSocket writeData:sendData withTimeout:-1 tag:0];
        }
    }
}

// 判断 userId 对应的用户是否在线
- (MiniSocket *)isBuddyOnline:(NSInteger)userId
{
    @synchronized([MainSocketDelegate connectedSocketsQueue])
    {
        // 遍历 connectedSocketQueue，找到该好友的 _sock
        for (MiniSocket *_sock in [MainSocketDelegate connectedSocketsQueue]) 
        {
            if (_sock.userId == userId)
            {
                return _sock;
            }
        }
        return nil;
    }
}

// 产生 listenPortPacket
- (NSData *)createListPortPacket:(NSInteger)userId listenPort:(NSInteger)listenPort ip:(NSData *)ip
{
    NSInteger hrdLen = sizeof(LISTENPORTHRD) + [ip length];
    LISTENPORTHRD *hrd = (LISTENPORTHRD *)NewPtr(hrdLen);
    hrd->type = CMD_FUN_LISTENPORT;
    hrd->operation = 0; // 任意数值
    hrd->userId = userId;
    hrd->listenPort = listenPort;
    hrd->ip_len = [ip length];
    char *hrdIpChar = (char *)hrd + sizeof(LISTENPORTHRD);
    [ip getBytes:hrdIpChar length:[ip length]];
    
    NSData *sendData = [[NSData alloc] initWithBytes:(char *)hrd length:hrdLen];
    
    DisposePtr((char *)hrd);
    
    return sendData;
}

// 把 NSInteger 的qq号转换为 NSString 的
- (NSString *)convertQQNumToString:(NSInteger)qqNum
{
#ifndef QQ_NUM_LEN
#define QQ_NUM_LEN 10
#endif
    NSMutableString *qqNumStr = [[NSMutableString alloc] initWithFormat:@"%ld", qqNum];
    while ([qqNumStr length] != QQ_NUM_LEN)
    {
        [qqNumStr insertString:@"0" atIndex:0];
    }
    return qqNumStr;
}

@end
